package cn.xinfei.xdecision.data.core.frame.executors.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpExecutorUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpExecutorUtil.class);


    /**
     * 解析接口变量
     */
    public static Object interfaceParseVariable(String parseStr, String jsonStr) {
        JSONObject json;
        try {
            if (jsonStr.contains("[") && jsonStr.contains("]")) {
                jsonStr = jsonStr.replace("[", "").replace("]", "");
            }
            json = JSONObject.parseObject(jsonStr);
        } catch (Exception e) {
            JSONArray jsonArray = JSONArray.parseArray(jsonStr);
            json = jsonArray.getJSONObject(0);
        }

        if (parseStr.contains(".[]")) {
            parseStr = parseStr.replace(".[]", "[]");
        }
        String[] strArr = parseStr.split("\\.");
        for (int i = 0; i < strArr.length - 1; i++) {
            if (strArr[i].contains("[]")) {
                jsonStr = jsonStr.replace(".[]", "[]");
                JSONArray jsonArray = json.getJSONArray(strArr[i]);
                json = jsonArray.getJSONObject(0);
            } else {

                json = json.getJSONObject(strArr[i]);
            }
        }
        Object value = null;
        if (json != null) {
            value = json.get(strArr[strArr.length - 1]);
        } else {
            LOGGER.info("parseStr = {} jsonStr = {} 解析结果为空", parseStr, jsonStr);
        }
        return value;
    }

    public static void main(String[] args) {
        Object s = interfaceParseVariable("payload.params.last_RiskTurndown_Days",
                "{\"msg\":\"success\",\"apiName\":\"/offline/queryNtpData\",\"code\":200,\"payload\":[{\"label\":\"ads_app_event_upload\"}],\"requestId\":\"12345678\",\"timestamp\":1689304006186}");

        System.out.println("S" + s);
    }


}
